package com.javacoo.sftp.client.internal;

import com.javacoo.sftp.client.api.SftpClient;
import com.javacoo.sftp.client.exception.SftpClientException;
import com.javacoo.sftp.client.template.SftpTemplate;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/**
 * Sftp客户端接口默认实现
 * <li></li>
 * @author duanyong@javacoo.com
 * @date 2020/5/14 13:31
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Slf4j
@Builder
public class DefaultSftpClient implements SftpClient {
    /** SftpTemplate连接池*/
    private SftpTemplatePool sftpTemplatePool;

    /**
     * 从sftp连接池获取连接并执行操作
     * <li></li>
     * @author duanyong@jccfc.com
     * @date 2020/5/14 10:29
     * @param key: 客户端配置KEY
     * @param handler: 处理器
     * @return: void
     */
    @Override
    public void run(String key,SftpClient.Handler handler) {
        SftpTemplate sftpTemplate = getClient(key).orElseThrow(()->new SftpClientException("客户端:{},获取sftp连接出错",key));
        try {
            handler.doHandle(sftpTemplate);
        }catch (Exception e) {
            log.error("客户端:{},异常:{}",key, e.getMessage());
            throw new SftpClientException("客户端:{},sftp发生异常", e,key);
        } finally {
            if (sftpTemplate != null) {
                sftpTemplatePool.releaseClient(key,sftpTemplate);
            }
        }
    }
    /**
     * 从sftp连接池获取连接并执行操作
     * <li></li>
     * @author duanyong@jccfc.com
     * @date 2020/5/14 10:29
     * @param key: 客户端配置KEY
     * @param handler: 处理器
     * @return: T
     */
    @Override
    public <T> T runAndReturn(String key, ReturnHandler<T> handler) {
        SftpTemplate sftpTemplate = getClient(key).orElseThrow(()->new SftpClientException("客户端:{},获取sftp连接出错",key));
        try {
            return handler.doHandle(sftpTemplate);
        } catch (Exception e) {
            log.error("客户端:{},异常:{}",key, e.getMessage());
            throw new SftpClientException("客户端:{},sftp发生异常", e,key);
        } finally {
            if (sftpTemplate != null) {
                sftpTemplatePool.releaseClient(key,sftpTemplate);
            }
        }
    }
    /**
     * 获取SftpTemplate
     * <li></li>
     * @author duanyong@jccfc.com
     * @date 2020/6/9 10:26
     * @param key: 渠道key
     * @return: com.jccfc.sftp.client.template.SftpTemplate
     */
    private Optional<SftpTemplate> getClient(String key){
        SftpTemplate client = null;
        //重试次数
        AtomicInteger retryCount = new AtomicInteger(this.sftpTemplatePool.getSftpPoolConfig().getRetryCount());
        while (client == null && retryCount.decrementAndGet() >= 0) {
            try {
                client = sftpTemplatePool.getClient(key);
            } catch (Exception e) {
                log.error("线程->{},从对象池中获client异常,还可以重试:{}次",Thread.currentThread().getName(),retryCount.get(),e);
            }
        }
        return Optional.ofNullable(client);
    }
}
